﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using QRCode.Common;

namespace QRCode.Controllers
{
    public class QRCodeController : Controller
    {
        private readonly IQRCode _iQRCode;

        public QRCodeController(IQRCode iQRCode)
        {
            _iQRCode = iQRCode;
        }

        public IActionResult Index(string id, string codeUrl, int pixel, string orgUrl = "官网地址：www.baidu.com")
        {



            string sourceImg = "Data\\qrCodeBack.jpg";
            Image bitmap1 = Image.FromFile(sourceImg); //底图

            Response.ContentType = "image/jpeg";
            Bitmap bitmap2 = _iQRCode.GetQRCode(codeUrl, pixel); //二维码图

            //从指定的System.Drawing.Image(bitmap1)创建新的System.Drawing.Graphics [图形算法]       
            Graphics g = Graphics.FromImage(bitmap1);

            g.DrawImage(bitmap2, 150, 280, 240, 240); //合并二维码

            Font font = new Font(new FontFamily("宋体"), 20, FontStyle.Bold);
            g.DrawString(id, font, new SolidBrush(Color.Black), 200, 190);  //添加文字

            Font font2 = new Font(new FontFamily("宋体"), 12, FontStyle.Bold);
            g.DrawString(orgUrl, font2, new SolidBrush(Color.White), 180, 765); //添加文字

            MemoryStream ms = new MemoryStream();
            bitmap1.Save(ms, ImageFormat.Jpeg);
            Response.Body.WriteAsync(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length));
            Response.Body.Close();
            return new EmptyResult();
        }


        public IActionResult GDITest()
        {
            string number = "编号:10000";
            string netbodyName = "杭二中";

            Bitmap bitmap1 = new Bitmap(300, 300);
         
            Graphics g = Graphics.FromImage(bitmap1);
            g.FillRectangle(Brushes.White, 0, 0, bitmap1.Width, bitmap1.Height);

            Bitmap bitmap2 = _iQRCode.GetQRCode("http://www.baidu.com", 10); //二维码图

            g.DrawImage(bitmap2, 12, 0, 280, 280); //合并二维码

            Font font = new Font(new FontFamily("宋体"), 12, FontStyle.Bold);

            SizeF numberSize = g.MeasureString(number, font);
            SizeF netbodySize = g.MeasureString(netbodyName, font);
           
            float numberX = (bitmap1.Width - numberSize.Width) / 2;
            float netbodyX = (bitmap1.Width - netbodySize.Width) / 2;

            g.DrawString(number, font, new SolidBrush(Color.Black), numberX, 255);  //添加文字
            g.DrawString(netbodyName, font, new SolidBrush(Color.Black), netbodyX, 275);  //添加文字

            MemoryStream ms = new MemoryStream();
            bitmap1.Save(ms, ImageFormat.Jpeg);
            Response.Body.WriteAsync(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length));
            Response.Body.Close();

            return  new EmptyResult();
        }

    }
}